package com.lmf.mock.starter.autoconfigure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmf.mock.starter.autoconfigure.entity.ProxyConfig;
import com.lmf.mock.starter.autoconfigure.mapper.ProxyConfigMapper;
import com.lmf.mock.starter.autoconfigure.service.ProxyConfigService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 代理配置服务实现
 */
@Service
public class ProxyConfigServiceImpl extends ServiceImpl<ProxyConfigMapper, ProxyConfig> implements ProxyConfigService {

    @Override
    public List<ProxyConfig> getEnabledConfigs() {
        QueryWrapper<ProxyConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("enabled", true);
        wrapper.orderByAsc("create_time");
        return list(wrapper);
    }

    @Override
    public ProxyConfig getConfigById(Long id) {
        return getById(id);
    }

    @Override
    public ProxyConfig getConfigByPathAndMethod(String path, String method) {
        QueryWrapper<ProxyConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("source_path", path);
        wrapper.eq("method", method);
        wrapper.eq("enabled", true);
        return getOne(wrapper);
    }

    @Override
    public ProxyConfig createConfig(ProxyConfig config) {
        config.setCreateTime(LocalDateTime.now());
        config.setUpdateTime(LocalDateTime.now());
        if (config.getEnabled() == null) {
            config.setEnabled(true);
        }
        if (config.getTimeout() == null) {
            config.setTimeout(5000);
        }
        if (config.getRetryCount() == null) {
            config.setRetryCount(0);
        }
        save(config);
        return config;
    }

    @Override
    public ProxyConfig updateConfig(ProxyConfig config) {
        config.setUpdateTime(LocalDateTime.now());
        updateById(config);
        return config;
    }

    @Override
    public boolean deleteConfig(Long id) {
        return removeById(id);
    }

    @Override
    public boolean toggleConfigStatus(Long id) {
        ProxyConfig config = getById(id);
        if (config != null) {
            config.setEnabled(!config.getEnabled());
            config.setUpdateTime(LocalDateTime.now());
            return updateById(config);
        }
        return false;
    }

    @Override
    public List<ProxyConfig> getConfigsByGroupId(Long groupId) {
        QueryWrapper<ProxyConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("group_id", groupId);
        wrapper.orderByAsc("create_time");
        return list(wrapper);
    }
}
